<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\HouseOption;
use Illuminate\Http\Request;
use \Illuminate\Support\Facades\Validator;

class HouseOptionController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     */
    public function index()
    {
        $data = HouseOption::all();
        return $this->success($data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     */
    public function store(Request $request)
    {
        $data = $request->post();

        $validator = Validator::make($data, [
            'name' => 'required',
            'values' => 'required',
            'required' => 'required',
            'type' => 'required'
        ]);

        if ($validator->fails()) {
            $errors = $validator->errors();
            return $this->error($errors->first());
        }

        $data['values'] = json_encode($data['values'], JSON_UNESCAPED_UNICODE);

        HouseOption::query()->create($data);

        return $this->success();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     */
    public function show($id)
    {
        $data = HouseOption::query()->find($id, ['name', 'values', 'type', 'required']);
        $data['values'] = json_decode($data['values'], true);
        return $this->success($data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     */
    public function update(Request $request, $id)
    {
        $data = $request->post();

        $validator = Validator::make($data, [
            'name' => 'required',
            'values' => 'required',
            'required' => 'required',
            'type' => 'required'
        ]);

        if ($validator->fails()) {
            $errors = $validator->errors();
            return $this->error($errors->first());
        }

        $data['values'] = json_encode($data['values'], JSON_UNESCAPED_UNICODE);

        $res = HouseOption::query()->where('id', $id)->update($data);

        if ($res) {
            return $this->success();
        }
        return $this->error();

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     */
    public function destroy($ids)
    {
        $ids = explode(',', $ids);
        HouseOption::query()->whereIn('id', $ids)->delete();

        return $this->success();
    }

    public function editHouseOptionStatus(Request $request)
    {
        $id = $request->post('id');
        $status = (HouseOption::query()->where('id', $id)->value('state') == 1) ? 0 : 1;
        if ($id) {
            HouseOption::query()->where('id', $id)->update(['state' => $status]);
            return $this->success();
        }

    }
}
